package com.fyzk.activity.main;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.App;
import com.fyzk.activity.fragment.DiscoverFragment;
import com.fyzk.activity.fragment.GoldDocumentaryFragment;
import com.fyzk.activity.fragment.GouCaiFragment;
import com.fyzk.activity.fragment.PersonalFragment;
import com.fyzk.activity.fragment.ScoreAwardFragment;
import com.fyzk.activity.lottery.recommend_order.MainDialogBean;
import com.fyzk.activity.lottery.recommend_order.WinningRankBean;
import com.fyzk.activity.popupwindow.WinningRankPopup;
import com.fyzk.base.IBaseActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.MainDialog;
import com.fyzk.net.Base64;
import com.fyzk.net.Commands;
import com.fyzk.net.ToolsAesCrypt;
import com.fyzk.utils.DateUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LogUtils;
import com.fyzk.utils.Utils;
import com.fyzk.utils.update.CustomerCalls;
import com.fyzk.utils.update.UpdateManager;
import com.fyzk.utils.update.VersionModel;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.pagercycle.ZJInfo;
import com.tyjc.lottery.BuildConfig;
import com.tyjc.lottery.R;
import com.wf.domain.UrlDef;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.x;

import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import razerdp.basepopup.BasePopupWindow;

public class MainGroupActivityI extends IBaseActivity implements
        android.view.View.OnClickListener, EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private static final String[] LOCATION_AND_STORAGE_AND_CAMERA = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    //当前显示的fragment
    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";

    private static final int RC_LOCATION_AND_STORAGE_AND_CAMERA_PERM = 123;
    private boolean isFirstResume = true;

    protected int index;

    private RadioGroup rg_main_opt;
    private RadioButton rb_goucai;
    private RadioButton rb_user;
    private RadioButton rb_gold;
    private RadioButton rb_score;
    private RadioButton rb_discover;

    private Fragment curFragment = null;
    private GouCaiFragment homeFragment;
    private ScoreAwardFragment scoreFragment;
    private GoldDocumentaryFragment goldDocumentaryFragment;
    private DiscoverFragment discoverFragment;
    private PersonalFragment userFragment;
    private WinningRankPopup winningRankPopup;//中奖榜单弹窗

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dj_activity_maingroup);
        rg_main_opt = findViewById(R.id.rg_main_opt);
        rb_goucai = findViewById(R.id.rb_goucai);
        rb_score = findViewById(R.id.rb_score);
        rb_gold = findViewById(R.id.rb_gold);
        rb_discover = findViewById(R.id.rb_discover);
        rb_user = findViewById(R.id.rb_user);

        rb_goucai.setOnClickListener(this);
        rb_score.setOnClickListener(this);
        rb_gold.setOnClickListener(this);
        rb_discover.setOnClickListener(this);
        rb_user.setOnClickListener(this);
        if(isProxy(this)){
            return;
        }
        if (null != savedInstanceState) {//简单处理内存重启fragment重叠的问题
            //获取“内存重启”时保存的fragment名字
            String saveName = "";
            if (savedInstanceState.containsKey(CURRENT_FRAGMENT))
                saveName = savedInstanceState.getString(CURRENT_FRAGMENT);

            homeFragment = (GouCaiFragment) getSupportFragmentManager().findFragmentByTag(GouCaiFragment.class.getName());
            scoreFragment = (ScoreAwardFragment) getSupportFragmentManager().findFragmentByTag(ScoreAwardFragment.class.getName());
            goldDocumentaryFragment = (GoldDocumentaryFragment) getSupportFragmentManager().findFragmentByTag(GoldDocumentaryFragment.class.getName());
            discoverFragment = (DiscoverFragment) getSupportFragmentManager().findFragmentByTag(DiscoverFragment.class.getName());
            userFragment = (PersonalFragment) getSupportFragmentManager().findFragmentByTag(PersonalFragment.class.getName());

            if (TextUtil.isEmpty(saveName)) {
                showDefaultFragment();
            } else {
                rb_goucai.setVisibility(MySharedPreferences.getInstance().getOpenStatus() ?
                        View.VISIBLE : View.GONE);
                if (null != homeFragment && saveName.equals(homeFragment.getClass().getName()))
                    setHomeCheck();
                else if (null != scoreFragment && saveName.equals(scoreFragment.getClass().getName()))
                    setScoreCheck();
                else if (null != goldDocumentaryFragment && saveName.equals(goldDocumentaryFragment.getClass().getName()))
                    setGoldCheck();
                else if (null != discoverFragment && saveName.equals(discoverFragment.getClass().getName()))
                    setDiscoverCheck();
                else if (null != userFragment && saveName.equals(userFragment.getClass().getName()))
                    setUserCenterCheck();
                else
                    showDefaultFragment();
            }

        } else {
            showDefaultFragment();
        }
        requestPermissions();
        requestDialog();
    }

    private void showDefaultFragment() {
        if (MySharedPreferences.getInstance().getOpenStatus()) {
            rb_goucai.setVisibility(View.VISIBLE);
            setHomeCheck();
        } else {
            setScoreCheck();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //“内存重启”时保存当前的fragment名字
        if (null != curFragment)
            outState.putString(CURRENT_FRAGMENT, curFragment.getClass().getName());
        super.onSaveInstanceState(outState);
    }

    /**
     * 获取位置，手机唯一识别码与相机权限
     * 先判断是否有权限，有权限让使用app，没有权限，不让使用。
     */
    @AfterPermissionGranted(RC_LOCATION_AND_STORAGE_AND_CAMERA_PERM)
    private void requestPermissions() {
        if (!hasPermissions()) {
            EasyPermissions.requestPermissions(this, "正在请求使用您的手机权限，是否继续?", RC_LOCATION_AND_STORAGE_AND_CAMERA_PERM, LOCATION_AND_STORAGE_AND_CAMERA);
        }
    }

    private boolean hasPermissions() {
        return EasyPermissions.hasPermissions(this, LOCATION_AND_STORAGE_AND_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            if (!EasyPermissions.hasPermissions(this, LOCATION_AND_STORAGE_AND_CAMERA)) {
                requestPermissions();
            }
        }
    }

    /**
     * 版本更新接口
     */
    private void getVersionByUrl() {
        String url = UrlDef.UPDATE_URL + BuildConfig.UPDATE_KEY;
        JSONObject request_json = new JSONObject();
        try {
            httpPostJsonNo(CommandUtil.UPDATE, "", request_json, false, url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void requestWiningRank() {
        JSONObject params = new JSONObject();
        httpPostJson(CommandUtil.ORDERWINRROUNDS, Commands.ORDERWINRROUNDS, params, false);
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.UPDATE:

                LogUtils.e("====UPDATE result====" + result);

                VersionModel beans = JSON.parseObject(resultBean.getData(), VersionModel.class);
                UpdateManager.getUpdateManager().getVersion(this, beans, "0");

                if (beans != null) {
                    if (!TextUtils.isEmpty(beans.getQr_url())) {
                        MySharedPreferences.getInstance().setQrUrl(beans.getQr_url());
                    }

                    if (!TextUtils.isEmpty(beans.getHandsel_content())) {
                        MySharedPreferences.getInstance().setHandselContent(beans.getHandsel_content());
                    }

                    VersionModel.Version model = beans.getVersion();
                    if (model != null && !TextUtils.isEmpty(model.getContent())) {
                        homeFragment.setNoticeText(model.getContent());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getCustomercalls())) {
                        MySharedPreferences.getInstance().setCustomerCalls(model.getCustomercalls());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getQQ())) {
                        MySharedPreferences.getInstance().setServiceQQ(model.getQQ());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getDrawContent())) {
                        MySharedPreferences.getInstance().setDrawContent(model.getDrawContent().replaceAll("\\\\n", "\n"));
                    }

                    String splashImageUrl = MySharedPreferences.getInstance().getSplashImageUrl();
                    if (model != null && !TextUtils.isEmpty(model.getImage_url()) && !splashImageUrl.equals(model.getImage_url())) {
                        MySharedPreferences.getInstance().setSplashImageUrl(model.getImage_url());
                    }
                    //客服微信图片暂时用跟启动图一样的
                    String qqImageUrl = MySharedPreferences.getInstance().getQQImageUrl();
                    if (model != null && !TextUtils.isEmpty(model.getImage_url()) && !qqImageUrl.equals(model.getImage_url())) {
                        MySharedPreferences.getInstance().setQQImageUrl(model.getImage_url());
                    }
                }

                //检测是否需要弹出中奖榜单弹窗
                CustomerCalls customerCalls = MySharedPreferences.getInstance().getCustomerCalls();
                if (customerCalls != null) {
                    String[] split = customerCalls.getPopup().split("\\|");
                    if (split.length > 1) {
                        Calendar calendar = Calendar.getInstance();
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                                0, 0, 0);
                        long todayStartMillis = calendar.getTimeInMillis();
                        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) + 1,
                                0, 0, 0);
                        long todayEndMills = calendar.getTimeInMillis();
                        long lastShowWinningPopup = MySharedPreferences.getInstance().getLastShowWinningPopup();
                        try {
                            if (TextUtils.equals("1", split[0]) && hour >= Integer.parseInt(split[1])
                                    && lastShowWinningPopup < todayStartMillis) {
                                requestWiningRank();
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case CommandUtil.ORDERWINRROUNDS:
                List<WinningRankBean> rankList = JSON.parseArray(resultBean.getData(), WinningRankBean.class);
                if (rankList != null && !rankList.isEmpty()) {
                    if (winningRankPopup == null) {
                        winningRankPopup = new WinningRankPopup(getContext());
                        winningRankPopup.setOnClickListener((popupWindow, view) -> {
                            popupWindow.dismiss();
                            MySharedPreferences.getInstance().setLastShowWinningPopup(System.currentTimeMillis());
                        });
                    }
                    winningRankPopup.setRankData(rankList);
                    winningRankPopup.showPopupWindow();
                }
                break;
            case CommandUtil.GETDIALOG:
                MainDialogBean dialogResult = JSON.parseObject(resultBean.getData(), MainDialogBean.class);
                if (dialogResult != null) {
                    MainDialog dialog = new MainDialog(MainGroupActivityI.this, dialogResult);
                    dialog.show();
                }
                break;
        }
    }

    protected void onFailure(int requestCode, String message) {
        LogUtils.e("====UPDATE message====" + message);
        onFailure(requestCode, "", message);
        switch (requestCode) {
            case CommandUtil.UPDATE:
                Utils.showToast(getContext(), message, this);
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (MySharedPreferences.getInstance().getOpenStatus()) {
            setHomeCheck();
        }
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_goucai:
                // 购彩大厅
                setHomeCheck();
                break;
            case R.id.rb_score:
                // 比分开奖
                setScoreCheck();
                break;
            case R.id.rb_gold:
                //大神推单
                setGoldCheck();
                break;
            case R.id.rb_discover:
                // 发现
                setDiscoverCheck();
                break;
            case R.id.rb_user:
                // 用户中心
                setUserCenterCheck();
                break;
        }
    }

    /**
     * 购彩大厅选中
     */
    private void setHomeCheck() {
        rg_main_opt.check(R.id.rb_goucai);
        App.isBaskOrder = false;
        if (homeFragment == null) {
            homeFragment = new GouCaiFragment();
        }
        changeFragment(curFragment, homeFragment, false, false,
                R.id.fl_main_content);
        curFragment = homeFragment;

        mImmersionBar.reset()
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .autoStatusBarDarkModeEnable(true)
                .statusBarColor(R.color.white)
                .init();
    }

    /**
     * 比分开奖
     */
    private void setScoreCheck() {
        rg_main_opt.check(R.id.rb_score);
        App.isBaskOrder = false;
        if (scoreFragment == null) {
            scoreFragment = new ScoreAwardFragment();
        }
        changeFragment(curFragment, scoreFragment, false, false,
                R.id.fl_main_content);
        curFragment = scoreFragment;

        mImmersionBar.reset().fitsSystemWindows(true).autoStatusBarDarkModeEnable(true).statusBarColor(R.color.top_bg).init();
    }

    /**
     * 大神推单
     */
    public void setGoldCheck() {
        rg_main_opt.check(R.id.rb_gold);
        App.isBaskOrder = false;
        if (null == goldDocumentaryFragment) {
            goldDocumentaryFragment = GoldDocumentaryFragment.newInstance();
        }
        changeFragment(curFragment, goldDocumentaryFragment, false, false,
                R.id.fl_main_content);
        curFragment = goldDocumentaryFragment;
        mImmersionBar.reset().fitsSystemWindows(true).autoStatusBarDarkModeEnable(true).statusBarColor(R.color.red).init();
    }

    /**
     * 发现
     */
    private void setDiscoverCheck() {
        rg_main_opt.check(R.id.rb_discover);
        App.isBaskOrder = false;
        if (discoverFragment == null) {
            discoverFragment = new DiscoverFragment();
        }
        changeFragment(curFragment, discoverFragment, false, false,
                R.id.fl_main_content);
        curFragment = discoverFragment;

        mImmersionBar.reset().fitsSystemWindows(true).autoStatusBarDarkModeEnable(true).statusBarColor(R.color.top_bg).init();
    }

    /**
     * 个人中心
     */
    private void setUserCenterCheck() {
        rg_main_opt.check(R.id.rb_user);
        App.isBaskOrder = false;
        if (userFragment == null) {
            userFragment = new PersonalFragment();
        }
        changeFragment(curFragment, userFragment, false, false,
                R.id.fl_main_content);
        curFragment = userFragment;

        mImmersionBar.reset().fitsSystemWindows(false).autoStatusBarDarkModeEnable(true).statusBarDarkFont(true).init();
    }

    private AlertDialog dialog;

    @Override
    protected void onResume() {
        super.onResume();
        String data = getIntent().getDataString();
        if (data != null && data.contains("html5back")) {
            setHomeCheck();
        }
        if (!isFirstResume) {
            if (!EasyPermissions.hasPermissions(this, LOCATION_AND_STORAGE_AND_CAMERA)) {
                EasyPermissions.requestPermissions(this, "正在请求使用您的手机权限，是否继续?", RC_LOCATION_AND_STORAGE_AND_CAMERA_PERM, LOCATION_AND_STORAGE_AND_CAMERA);
            }
        }
        isFirstResume = false;
        if(!checkProxy()){
            getVersionByUrl();
        }
    }

    @Override
    public void onBackPressed() {
        MainGroupActivityI.exitTiShi(this);
    }

    /**
     * 退出提示对话框
     */
    public static void exitTiShi(final Activity activity) {
        quit(activity);
    }

    /**
     * 退出程序
     *
     * @return
     */
    private static void quit(final Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("提示");
        builder.setMessage("你确定要退出吗？");
        builder.setPositiveButton("确定", new OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                activity.finish();
                AppLotteryInfos.clear();
                ViewCallBack.getInstance().countDownObjs.clear();
                ActivityTaskManager.getInstance().closeAllActivity();
                System.exit(0);
            }

        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 权限申请成功
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    /**
     * 权限申请失败
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {//点击了不再提醒
            AppSettingsDialog.Builder builder = new AppSettingsDialog.Builder(this);
            builder.setTitle("权限申请");
            builder.setRationale("当前应用缺少必要权限。\n\n请在手机设置中开启所需权限，以便正常使用");
            AppSettingsDialog build = builder.build();
            build.show();
        } else {
            if (!EasyPermissions.hasPermissions(this, LOCATION_AND_STORAGE_AND_CAMERA)) {
                requestPermissions();
            }
        }
    }

    /**
     * 再次申请时，点击确认按钮
     *
     * @param requestCode
     */
    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    /**
     * 再次申请时，点击取消按钮
     *
     * @param requestCode
     */
    @Override
    public void onRationaleDenied(int requestCode) {
        finish();
    }


    private static boolean isProxy(Context context) {
        final boolean IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        String proxyAddress;
        int proxyPort;
        if (IS_ICS_OR_LATER) {
            proxyAddress = System.getProperty("http.proxyHost");
            String portStr = System.getProperty("http.proxyPort");
            proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
        } else {
            proxyAddress = android.net.Proxy.getHost(context);
            proxyPort = android.net.Proxy.getPort(context);
        }

        return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
    }


    private void requestDialog() {
        try {
            if (!DateUtils.isSameData(System.currentTimeMillis(), MySharedPreferences.getInstance().getDialogTime())) {
                JSONObject request_json = new JSONObject();
                httpPostJson(CommandUtil.GETDIALOG, "getNotify", request_json, false, UrlDef.getDialog);
            }
        } catch (Exception e) {
        }
    }

    private boolean checkProxy(){
        if (isProxy(this)) {
            dialog = new AlertDialog.Builder(this)
                    .setMessage("服务暂不可用，请检查网络是否使用了代理，关闭代理后重试")
                    .setPositiveButton("知道了", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityTaskManager.getInstance().closeAllActivity();
                        }
                    })
                    .setCancelable(false)
                    .create();
            dialog.show();
            return true;
        }else {
            return false;
        }
    }
}
